package svc

import (
	"fmt"
	"github.com/google/uuid"
	"strings"
)

func (h *SseHandler) BindUid(clientId uuid.UUID, uid string) {
	h.clients[clientId].Uid = uid
}

func (h *SseHandler) JoinGroup(clientId uuid.UUID, groupId string) {
	clientGroupKey := fmt.Sprintf("%s-%s", clientId, groupId)
	h.group.LoadOrStore(clientGroupKey, groupId)
}

func (h *SseHandler) LivingGroup(clientId uuid.UUID, groupId string) {
	clientGroupKey := fmt.Sprintf("%s-%s", clientId, groupId)
	h.group.Delete(clientGroupKey)
}

func (h *SseHandler) SendToOne(clientId uuid.UUID, message string) {
	h.clients[clientId].Writer <- message
}

func (h *SseHandler) SendToGroup(groupId string, message string) {
	h.group.Range(func(key, value interface{}) bool {
		if value.(string) == groupId {
			sk := strings.Split(key.(string), "-")
			uid, err := uuid.Parse(sk[0])
			if err == nil {
				h.clients[uid].Writer <- message
			}
		}
		return true
	})
}

func (h *SseHandler) GetAllGroup() []string {
	res := make([]string, 0)
	h.group.Range(func(key, value any) bool {
		res = append(res, value.(string))
		return true
	})
	return res
}

func (h *SseHandler) GetClientCountByGroup(groupId string) int64 {
	count := 0
	h.group.Range(func(key, value any) bool {
		if value == groupId {
			count++
		}
		return true
	})
	return int64(count)
}

func (h *SseHandler) GetUidByGroup(groupId string) []string {
	uids := make([]string, 0)
	h.group.Range(func(key, value any) bool {
		if key.(string) == groupId {
			sk := strings.Split(key.(string), "-")
			uids = append(uids, sk[0])
		}
		return true
	})

	return uids
}

func (h *SseHandler) GetClientIdByGroup(groupId string) []string {
	clientId := make([]string, 0)
	h.group.Range(func(key, value any) bool {
		if key.(string) == groupId {
			sk := strings.Split(key.(string), "-")
			uid, err := uuid.Parse(sk[0])
			if err == nil {
				clientId = append(clientId, uid.String())
			}
		}
		return true
	})
	return clientId
}
